package com.example.demo.core.web.core.model;

import com.baomidou.mybatisplus.solon.plugins.pagination.Page;
import lombok.Getter;
import lombok.Setter;

/**
 * @author airhead
 */
@Setter
@Getter
public class PageReq {
  private static final long serialVersionUID = -367774852100267476L;
  private Integer page;
  private Integer pageSize;

  private Integer pages;
  private Integer offset;

  public PageReq() {
    this.page = 1;
    this.pageSize = 10;
    this.offset = 0;
  }

  /**
   * 初始化
   *
   * @param pageReq
   * @return
   */
  public static PageReq build(PageReq pageReq) {
    if (pageReq == null) {
      return new PageReq();
    }

    if (pageReq.getPage() == null) {
      pageReq.setPage(1);
    }

    if (pageReq.getPageSize() == null) {
      pageReq.setPageSize(10);
    }

    pageReq.setOffset((pageReq.getPage() - 1) * pageReq.getPageSize());

    return pageReq;
  }

  public void init() {
    if (this.page == null) {
      this.page = 1;
    }

    if (this.pageSize == null) {
      this.pageSize = 10;
    }

    this.offset = (page - 1) * pageSize;
  }

  public void paginate(Integer count) {
    if (this.page == null) {
      this.page = 1;
    }

    if (this.pageSize == null) {
      this.pageSize = 10;
    }

    this.pages = count / pageSize + 1;
    this.offset = (page - 1) * pageSize;
  }

  public <T> Page<T> buildPage() {
    // 设置页数
    Page<T> page = new Page<>();
    // 设置页数
    if (getPage() != null && getPageSize() != null) {
      page.setSize(getPageSize());
      page.setCurrent(getPage());
    } else {
      page.setSize(10);
      page.setCurrent(1);
    }

    return page;
  }

  public <T> Page<T> buildPage(Integer count) {
    // 设置页数
    Page<T> page = new Page<>();
    // 设置页数
    if (getPage() != null && getPageSize() != null) {
      page.setSize(getPageSize());
      page.setCurrent(getPage());
    } else {
      page.setSize(10);
      page.setCurrent(1);
    }

    // 计算总数和页面数据
    page.setTotal(count);
    page.setPages(count / pageSize + 1);

    return page;
  }
}
